﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Net;
using MT.Common.Log;

namespace MT.Mvc.Core.Filters
{
    public class GlobalActionFilter : Microsoft.AspNetCore.Mvc.Filters.IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            return;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ModelState.IsValid) return;

            //foreach (var item in context.ModelState.Values)
            //{
            //    foreach (var error in item.Errors)
            //    {
            //        msg += error.ErrorMessage + "|";
            //    }
            //}
            context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            var message = context.ModelState.Values.FirstOrDefault()?.Errors.FirstOrDefault()?.ErrorMessage.ToString();
            if(string.IsNullOrEmpty(message))
            {
                // context.Result = new ObjectResult(new { Code = (int)ErrorCode.InvalidParameter, Msg = context.ModelState.Values.FirstOrDefault().Errors.FirstOrDefault().Exception.Message.ToString() });
                throw new  ApplicationException(context.ModelState.Values.FirstOrDefault()?.Errors.FirstOrDefault()?.Exception.Message.ToString());
            }
            else
            {
                context.Result = new ObjectResult(new { Code = (int)ErrorCode.InvalidParameter, Msg = message });
                   
            }
            return;
        }
    }
}
